<template>
  <div class="login-container">
    <h1>登录</h1>
    <form @submit.prevent="handleLogin" ref="loginFormRef">
      <div class="form-group">
        <label for="username">账号</label>
        <input id="username" v-model="loginForm.username" required>
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input type="password" id="password" v-model="loginForm.password" required>
      </div>
      <div class="form-group">
        <label for="captcha">验证码</label>
        <input id="captcha" v-model="loginForm.captcha" required>
      <div>
        <img class="captcha" :src="captchaUrl" style="height: 40px;" @click="refresh" alt="验证码">
      </div>
      </div>
      <button type="submit">登录</button>
    </form>
  </div>
</template>

<script setup>
import { reactive ,ref} from 'vue';
import { login } from "@/api/LoginApi.js";
import { save as saveToken } from "@/api/JwtApi";
import { useRouter } from 'vue-router';
//获取路由转发器
const router = useRouter();

const loginFormRef = ref(null);//表单实例
const loginForm = reactive({
  username: '',
  password: '',
  captcha:''
});//表单数据

async function handleLogin() {
  // 检查表单字段是否为空
  if (!loginForm.username || !loginForm.password || !loginForm.captcha) {
    alert('请填写所有字段');
    return;
  }

  try {
    const response = await login(loginForm);
    if (response.success) {
      saveToken(response.data);
      router.push('/main/home');
    } else {
      alert(response.error || '登录失败');
    }
  } catch (error) {
    alert('登录过程中发生错误');
    console.error('Error during login:', error);
  }
}

//获取验证码地址
const captchaUrl = ref("/api/customer/captcha");
//刷新验证码
function refresh() {
  captchaUrl.value = "/api/customer/captcha?id=" + Math.random();
}
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  width: 100%;
}

.form-group {
  margin-bottom: 15px;
  width: 100%;
}

label {
  display: block;
  margin-bottom: 5px;
}

input {
  width: 90%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  width: 90%;
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>
